<?php
/**
 * @Notes:【】
 * @User: zwc
 * @Date: 2022-04-30 16:17
 */

namespace App\Controller\Ws;

use App\Middleware\ws\WebSocketAuthMiddleware;
use App\Repository\WebSocket\UsersData;
use App\Service\WebSocket\SocketClientService;
use Hyperf\Contract\OnCloseInterface;
use Hyperf\Contract\OnMessageInterface;
use Hyperf\Contract\OnOpenInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\WebSocketServer\Context;
use Swoole\WebSocket\Frame;
use Swoole\Http\Request;
        
/**
 * @Middleware(WebSocketAuthMiddleware::class)
 */
class WsController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
{
    public function onMessage($server, Frame $frame): void
    {
        //推送
        $server->push($frame->fd, json_encode([
            "event" => "connect",
            "content" => [
                "ping_interval" => 20,
                "ping_timeout" => 20 * 3,
            ],
        ]));

        $result = json_decode($frame->data, true);

        // 判断是否为心跳检测
        if ($result['event'] == 'heartbeat') {
            $server->push($frame->fd, json_encode(['event' => "heartbeat", 'content' => "pong"]));
            return;
        }
        
    }

    public function onClose($server, int $fd, int $reactorId): void
    {
        var_dump('closed');
        $res = $this->SocketClientService->unbind($fd);
    }

    /**
     * @Inject()
     * @var SocketClientService
     */
    protected $SocketClientService;

    public function onOpen($server, Request $request): void
    {
        //推送
        $server->push($request->fd, json_encode([
            "event" => "connect",
            "content" => [
                "ping_interval" => 20,
                "ping_timeout" => 20 * 3,
            ],
        ]));

        $userData = UsersData::get();
        //绑定
        $this->SocketClientService->bind($request->fd, $userData, 1);
    }
}